import java.util.Comparator;
import java.util.PriorityQueue;

class MyTimerTask implements Comparable<MyTimerTask>{
    private Runnable task;
    private long delay;

    public MyTimerTask(Runnable task, long delay) {
        this.task = task;
        this.delay = delay;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.delay - o.delay);
    }

    public Runnable getTask() {
        return task;
    }

    public long getDelay() {
        return delay;
    }
}

class MyTimer {
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();

    public MyTimer() {
        Thread t = new Thread(() -> {
            try {
                while(true) {
                    synchronized (this) {
                        while (queue.isEmpty()) {
                            this.wait();
                        }
                        MyTimerTask task = queue.peek();
                        if(task.getDelay() > System.currentTimeMillis()) {
                            this.wait(task.getDelay() - System.currentTimeMillis());
                        } else {
                            task.getTask().run();
                            queue.poll();
                        }
                    }
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        t.start();
    }

    public synchronized void schedule(Runnable task, long delay) {
        MyTimerTask timerTask = new MyTimerTask(task, System.currentTimeMillis() + delay);
        queue.offer(timerTask);
        this.notify();
    }
}

class test implements Comparator<MyTimerTask> {

    @Override
    public int compare(MyTimerTask o1, MyTimerTask o2) {
        return (int) (o1.getDelay() - o2.getDelay());
    }
}

public class demo4 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(()->{
            System.out.println(1000);
        },1000);
        timer.schedule(()->{
            System.out.println(3000);
        },3000);
        timer.schedule(()->{
            System.out.println(2000);
        },2000);
    }
}
